package com.atguigu.crud.controller;

/*
处理员工的CRUD请求
* */

import com.atguigu.crud.bean.Employee;
import com.atguigu.crud.bean.Msg;
import com.atguigu.crud.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //删除用户
    //单个用户 1
    //多个用户 1-2-3
    @RequestMapping(value = "/emp/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmpById(@PathVariable("ids")String ids) {
        if (ids.contains("-")) {
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //组装id 的集合
            for (String str_id : str_ids) {
                del_ids.add(Integer.parseInt(str_id));
            }
            employeeService.deleteBatch(del_ids);
        }else {
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }


    //员工更新方法
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg saveEmp(Employee employee){
        employeeService.updateEmp(employee);
        return Msg.success();
    }



    //根据ID查询员工信息
    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id")Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }


    //判断用户名是否可用
    @ResponseBody
    @RequestMapping("/checkuser")
    public Msg checkUser(@RequestParam("empName")String empName){
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if (!empName.matches(regx)){
            return Msg.fail().add("va_msg","用户名必须是2-5位中文或者6-16位英文和数字的组合");
        }
        boolean b = employeeService.checkUser(empName);
        if (b){
            return  Msg.success();
        }else{
            return Msg.fail().add("va_msg","用户名不可用");
        }
    }


    /*
    * 员工保存功能
    * */
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    //@Valid表示数据保存时，需要通过后端Pattern校验
    //result存放后端校验后的返回结果
    public Msg saveEmp(@Valid  Employee employee, BindingResult result){
        boolean b = employeeService.checkUser(employee.getEmpName());
        Map<String, Object> map = new HashMap<>();
        System.out.println(b);
        if (b) {
            if (result.hasErrors()) {
                //检验失败的话，需要返回校验错误的信息
                List<FieldError> errors = result.getFieldErrors();
                for (FieldError error : errors) {
                    System.out.println("错误的字段名：" + error.getField());
                    System.out.println("错误信息：" + error.getDefaultMessage());
                    map.put(error.getField(), error.getDefaultMessage());
                }
                return Msg.fail().add("error", map);
            } else {
                employeeService.saveEmp(employee);
                return Msg.success();
            }
        }else {
            return Msg.fail().add("error","用户名重复");
        }
    }

/*
*ResponseBody需要正常使用，需要导入jackson包
* 查询员工数据，返回json
* */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
        //查询前使用分页插件进行分页
        PageHelper.startPage(pn,5);
        //employeeService调用查询去全部用户方法
        List<Employee> emps = employeeService.getAll();
        //使用PageInfo包装后的结果，具有详细的分页信息，包括查询数据
        //连续显示5页
        PageInfo pageInfo = new PageInfo(emps,5);
        //返回json，将数据传送到页面
        return Msg.success().add("pageInfo",pageInfo);
    }


    /*
    查询员工数据，分页查询
    返回页面数据
    * */
    //@RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        //查询前使用分页插件进行分页
        PageHelper.startPage(pn,5);
        //employeeService调用查询去全部用户方法
        List<Employee> emps = employeeService.getAll();
        //使用PageInfo包装后的结果，具有详细的分页信息，包括查询数据
        //连续显示5页
        PageInfo pageInfo = new PageInfo(emps,5);
        //通过model，将数据传送到页面
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

}
